const Sequelize = require('sequelize')
const Op = Sequelize.Op;

const sequelize = require('../db');

const Model = sequelize.define('stat_performance',
  {
      sub_type: { type: Sequelize.STRING, },
      url: { type: Sequelize.STRING },
      link: { type: Sequelize.STRING },
      time_count: { type: Sequelize.INTEGER, },
      initiator_type: { type: Sequelize.STRING, },
      ip: { type: Sequelize.STRING, },
      ua: { type: Sequelize.STRING, },
  },
  {
    tableName: 'stat_performance',
    // 不要忘记启用时间戳！
    timestamps: true,

    // 不想要 false
    createdAt: 'create_time',

    // 想要 updatedAt 但是希望名称叫做 updateTimestamp
    updatedAt: false
  }
);

module.exports.add = async (data) => await Model.create(data)
module.exports.addBatch = async (datas) => await Model.bulkCreate(datas)

module.exports.del = async (id) => await Model.destroy({ where: { id } })


module.exports.update = async (data) => {
  let newUser = {...data}
  delete newUser['id']
  return await Model.update({ ...newUser }, {
      where: { id: data.id }
  })
}

module.exports.findOne = async (condition) => {
  let users = await Model.findAll({ where: condition })
  return users[0]
}

module.exports.findAll = async (condition = {}) => {
  return await Model.findAll({ where: condition })
}

module.exports.getLoadList = async ({limit=10, offset=0}) => {
  return await Model.findAndCountAll({
      limit,
      offset,
      order: [['time_count', 'DESC']],
      where: {
          sub_type: {
              [Op.eq]: 'loadTime'
          }
      }
  })
}
module.exports.getResourceLoadList = async ({limit=10, offset=0}) => {
  return await Model.findAndCountAll({
      limit,
      offset,
      order: [['time_count', 'DESC']],
      where: {
          sub_type: {
              [Op.eq]: 'resourceTime'
          }
      }
  })
}